import React, { useEffect, useState, useRef } from 'react';
import { connect, history } from 'umi';
import { Form, Button, Col, Row, Space, Card, notification } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';
import EditorForm from '@/components/EditorForm';
import uploadOss from '@/utils/aliOssUpload';
import SelectAccount from './components/SelectAccount';
import SelectGath from './components/SelectGath';
import PopImgShow from '@/components/PopImgShow';
import TableDataBlock from '@/components/TableDataBlock';
import moment from 'moment';
import dayjs from 'dayjs';
import PackagingModel from '@/components/PackagingModel';
import MaterialModel from '@/components/MaterialModel';
import MainAdminTable from '@/components/MainAdminTable';
import { dateDisabled } from '@/common/regular';
import ShareImage from '@/assert/image/shareImageCode.png';
import './index.less';

const CreateLive = (props) => {
  const { history, loading, dispatch } = props;
  const { location } = history;
  const { query } = location;
  const { id, handleType = 'edit' } = query;
  const [data, setData] = useState({});
  const packagingRef = useRef(null);
  const materialRef = useRef(null);
  const EditContent = useRef(null);
  const { goodsPackageList = [], materialInfoList = [] } = data;
  const [form] = Form.useForm();
  const [list, setList] = useState([]);
  const [commission, setCommission] = useState([]);
  const [gatherList, setGatherList] = useState([]);
  const [MainAdminList, setMainAdminList] = useState([]);
  const [helpAdminList, sethelpAdminList] = useState([]);
  const [defaultSetting, setDefaultSetting] = useState({
    liveType: 'video',
    screenType: 'horizontal',
    needReplay: true,
    warmUpType: 'video',
    upType: 'now',
    showFlag: '1',
    priceType: 'free',
    signFlag: '0'
  });
  const { liveType, screenType, warmUpType, upType, showFlag, priceType, signFlag } = defaultSetting;
  const [content, setContent] = useState(''); // 输入的富文本内容
  const [modelVisible, setModelVisible] = useState(false);
  // 新增修改 传id修改 不传id新增
  const [gatherVisible, setGatherVisible] = useState(false);
  const { content: oldContent } = data;
  useEffect(() => {
    if (id) {
      dispatch({
        type: 'liveStreaming/fetchLiveDetail',
        payload: { goodsId: id },
        callback: (e) => {
          const {
            goodsBaseInfo = {},
            goodsPackageList = [],
            liveInfo = {},
            adminInfoList = [],
            materialInfoList = [],
          } = e;
          const { startTime, endTime } = liveInfo;
          const { content, picture, upType, upDelayTime } = goodsBaseInfo;
          setData({
            ...goodsBaseInfo,
            ...liveInfo,
            cover: picture,
            adminInfoList,
            endTime: moment(endTime, 'YYYY-MM-DD HH:mm'),
            startTime: moment(startTime, 'YYYY-MM-DD HH:mm'),
            upDelayTime: upType === 'delay' ? moment(upDelayTime, 'YYYY-MM-DD HH:mm:ss') : '',
            goodsPackageList,
            materialInfoList,
          });
        },
      });
    }
  }, []);
  useEffect(() => {
    if (id && data.id) {
      const { adminInfoList = [], mainAdminInfo = {} } = data
      setList(adminInfoList);
      if (mainAdminInfo.id) {
        setGatherList([data.mainAdminInfo]);
      }
      if (id) {
        form.setFieldsValue({
          liveType: data.liveType,
          screenType: data.screenType,
          needReplay: data.needReplay === '1' ? true : false,
          warmUpType: data.warmUpType,
          upType: data.upType,
          showFlag: data.showFlag,
          priceType: data.priceType,
        })
      }
      setDefaultSetting({
        liveType: data.liveType,
        screenType: data.screenType,
        needReplay: data.needReplay === '1' ? true : false,
        warmUpType: data.warmUpType,
        upType: data.upType,
        showFlag: data.showFlag,
        priceType: data.priceType,
      });
      EditContent.current.reloadEdit();
    }
  }, [data]);
  const fetchRoleEdit = () => {
    let goodsPackageList = packagingRef.current.getPackaging();
    let goodsPackageFlag = goodsPackageList.reduce((item, val) => {
      if (!item) {
        return item;
      } else {
        if (val.chooseType === 'any' && (!val.chooseAmount || val.chooseAmount === 0)) {
          console.log(val);
          notification.warning({
            message: '错误提示',
            description: `${goodsType_status[val.packageGoodsType]} 选择任何后 打包数量不能为0`,
          });
          return false;
        } else {
          return item;
        }
      }
    }, true);
    if (!goodsPackageFlag) {
      return;
    } else if (!content) {
      notification.warning({
        message: '错误提示',
        description: `请填写详情`,
      });
    } else {
      form.validateFields().then(async (values) => {
        const { picture, warmUp } = values;
        const materialIdList = materialRef.current.getMaterial();
        let img = await uploadOss(picture);
        let warmVideo = await uploadOss(warmUp);
        const {
          startTime,
          endTime,
          liveType,
          screenType,
          needReplay,
          warmUpType,
          goodsDesc,
          goodsName,
          showFlag,
          upType,
          upDelayTime,
          price,
          priceType,
          oriPrice,
          minPrice,
        } = values;

        dispatch({
          type: 'liveStreaming/fakeSaveLive',
          payload: {
            id: handleType === 'edit' ? id : '',
            liveInfo: {
              adminIds: list
                .map((item) => {
                  return item.id;
                })
                .toString(),
              mainAdminId: gatherList
                .map((item) => {
                  return item.id;
                })
                .toString(),
              startTime: startTime.format('YYYY-MM-DD HH:mm'),
              endTime: endTime.format('YYYY-MM-DD HH:mm'),
              liveType,
              screenType,
              needReplay: needReplay ? '1' : '0',
              warmUpType,
              warmUp: warmVideo.toString(),
            },
            goodsBaseInfo: {
              content,
              goodsDesc,
              picture: img.toString(),
              goodsName,
              id: handleType === 'edit' ? id : '',
              showFlag,
              upType,
              upDelayTime:
                upType === 'delay' ? moment(upDelayTime).format('YYYY-MM-DD HH:mm:ss') : '',
              price,
              priceType,
              oriPrice,
              minPrice,
              materialIdList,
            },
            goodsPackageList,
            // informationCollectionId: gatherList
            //   .map((item) => {
            //     return item.id;
            //   })
            //   .toString(),
          },
          callback: () => {
            history.goBack();
          },
        });
      });
    }
  };
  const getColumns = [
    {
      title: '姓名',
      dataIndex: 'username',
    },
    {
      title: '头像',
      dataIndex: 'profile',
      render: (e) => {
        return <PopImgShow width={24} url={e}></PopImgShow>;
      },
    },
  ];
  const ChatGathSet = (props) => {
    const { list = [] } = props;
    return (
      <Row style={{ marginBottom: 24 }}>
        <Col offset={6} gutter={[24, 24]}>
          <Button
            onClick={() => {
              setGatherVisible({ show: true, details: list });
            }}
          >
            +添加讲师
          </Button>
        </Col>
        <></>
        {list.length > 0 ? (
          <Col style={{ marginTop: 12 }} offset={6} span={18}>
            <TableDataBlock
              cardProps={{ title: '讲师' }}
              loading={loading}
              columns={getColumns}
              rowKey={(record) => `${record.id}`}
              list={list}
            ></TableDataBlock>
          </Col>
        ) : null}
      </Row>
    );
  };
  const ChatNameSet = (props) => {
    const { list = [] } = props;

    return (
      <Row style={{ marginBottom: 24 }}>
        <Col offset={6} gutter={[24, 24]}>
          <Button
            onClick={() => {
              setModelVisible({ show: true, details: list });
            }}
          >
            +添加助教
          </Button>
        </Col>
        <></>
        {list.length > 0 ? (
          <Col style={{ marginTop: 12 }} offset={6} span={18}>
            <TableDataBlock
              cardProps={{ title: '助教' }}
              loading={loading}
              columns={getColumns}
              rowKey={(record) => `${record.id}`}
              list={list}
            ></TableDataBlock>
          </Col>
        ) : null}
      </Row>
    );
  };

  function disabledDateTime(current) {
    console.log(current, 1231233123);
    // 获取当前时间
    const currentDate = new Date();
    const currentHour = currentDate.getHours();
    const currentMinute = currentDate.getMinutes();
    if (moment(current).isAfter(currentDate, 'day')) {
      return null;
    } else if (moment(current).isBefore(currentDate, 'day')) {
      return {
        disabledHours: () => Array.from({ length: 24 }, (_, i) => i),
        disabledMinutes: () => Array.from({ length: 60 }, (_, i) => i),
      };
    } else if (moment(current).hour() > moment(currentDate).hour()) {
      return {
        disabledHours: () => Array.from({ length: currentHour }, (_, i) => i),
      };
    } else {
      return {
        disabledHours: () => Array.from({ length: currentHour }, (_, i) => i),
        disabledMinutes: () => Array.from({ length: currentMinute }, (_, i) => i),
      };
    }
  }

  const screenObj = {
    video: {
      horizontal: (
        <Space>
          <div>横屏直播</div>{' '}
          <div style={{ color: '#999' }}>视频比例为16:9，适用于企业/PPT宣讲等场景</div>
        </Space>
      ),
      vertical: (
        <Space>
          <div>竖屏直播</div>{' '}
          <div style={{ color: '#999' }}>视频比例为9:16，适用于泛娱乐化教学、带货等场景</div>
        </Space>
      ),
    },
    replay: {
      horizontal: (
        <Space>
          <div>横屏直播</div>{' '}
          <div style={{ color: '#999' }}>视频比例为16:9，利用录制视频进行仿直播</div>
        </Space>
      ),
      vertical: (
        <Space>
          <div>横屏直播</div>{' '}
          <div style={{ color: '#999' }}>视频比例为9:16，利用录制视频进行仿直播</div>
        </Space>
      ),
    },
    voice: {
      horizontal: (
        <Space>
          <div>横屏直播</div>{' '}
          <div style={{ color: '#999' }}>支持课件展示，无需出镜，仅通过语音进行直播</div>
        </Space>
      ),
    },
  }[liveType];

  const formItems = [
    {
      label: '直播类型',
      name: 'liveType',
      type: 'radio',
      select: {
        video: '视频',
        // replay: '录播直播', voice: '语音直播'
      },
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          liveType: e.target.value,
        });
        form.setFieldValue('screenType', 'horizontal');
      },
    },
    {
      label: '展示方式',
      name: 'screenType',
      direction: 'vertical',
      type: 'radio',
      select: screenObj,
    },
    {
      label: '直播名称',
      name: 'goodsName',
    },
    {
      label: '商品明细',
      name: 'goodsDesc',
      type: 'textArea',
      rules: [{ required: false }],
      placeholder: '商品对应内容',
    },
    {
      label: '开始时间',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      showTime: 'HH:mm',
      disabledDate: dateDisabled,
      disabledTime: disabledDateTime,
      name: 'startTime',
    },
    {
      label: '结束时间',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      disabledDate: dateDisabled,
      disabledTime: disabledDateTime,
      showTime: 'HH:mm',
      name: 'endTime',
    },
    {
      label: '设置封面',
      name: 'picture',
      // maxFile: 1,
      type: 'upload',
      extra:
        '建议图片比例16:9，支持 jpg、png 格式，大小不超过5MB，最佳分辨率750*422px,并自动取第一张做直播宣传封面',
    },
    {
      label: '暖场类型',
      name: 'warmUpType',
      type: 'radio',
      select: { video: '视频', image: '图片' },
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          warmUpType: e.target.value,
        });
      },
    },
    {
      label: '暖场视频',
      name: 'warmUp',
      maxFile: 1,
      type: 'videoUpload',
      visible: warmUpType === 'video',
      extra: '支持mp4，avi，wmv，mov，flv，rmvb，3gp，m4v，mkv格式；文件最大不超过5G',
    },
    {
      label: '暖场图',
      name: 'warmUp',
      visible: warmUpType === 'image',
      extra: '建议图片比例16:9，支持 jpg、png 格式，大小不超过5MB，最佳分辨率750*422px',
      maxFile: 1,
      type: 'upload',
    },
    {
      label: '分享图',
      name: 'shareImg',
      extra: (
        <div>
          建议图片分辨率为560x728,分享码位于右下角居下40px居右32px。如下图：
          <div style={{ marginTop: 12 }}>
            <PopImgShow width={80} url={ShareImage}></PopImgShow>
          </div>
        </div>
      ),
      maxFile: 1,
      type: 'upload',
      rules: [{ required: false }],
    },
    // {
    //   label: '直播宣传封面',
    //   name: 'cover',
    //   maxFile: 1,
    //   type: 'upload',
    //   extra: '建议图片比例25:8，支持 jpg、png 格式，大小不超过5MB，最佳分辨率750*240px ',
    //   rules: [{ required: false }],
    // },
    {
      type: 'noForm',
      rules: [{ required: false }],
      formItem: <ChatGathSet list={gatherList}></ChatGathSet>,
    },
    {
      type: 'noForm',
      rules: [{ required: false }],
      formItem: <ChatNameSet list={list}></ChatNameSet>,
    },
    {
      label: '回放',
      name: 'needReplay',
      type: 'switch',
    },
    {
      type: 'noForm',
      formItem: (
        <Row>
          <Col span={6}>
            {' '}
            <div style={{ textAlign: 'right' }} className="">
              <span style={{ color: '#ff4d4f' }}>*</span>直播详情:
            </div>
          </Col>
          <Col span={18} style={{ paddingLeft: 4 }}>
            <EditorForm
              ref={EditContent}
              initEditor={id ? false : true}
              content={oldContent}
              editCallback={(val) => setContent(val)}
            ></EditorForm>
          </Col>
        </Row>
      ),
    },
    {
      type: 'noForm',
      formItem: (
        <MaterialModel
          defaultDataList={materialInfoList}
          ref={materialRef}
          detail={data}
        ></MaterialModel>
      ),
    },
  ];

  const formItemsGroup3 = [
    {
      label: '售卖方式',
      name: 'priceType',
      type: 'radio',
      select: {
        free: '免费',
        money: '付费',
      },
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          priceType: e.target.value,
        });
      },
    },
    {
      label: '原价',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      name: 'oriPrice',
      type: 'number',
      visible: priceType === 'money',
    },
    {
      label: '售价',
      name: 'price',
      rules: [
        { required: true },
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      type: 'number',
      visible: priceType === 'money',
    },
    {
      label: '底价',
      name: 'minPrice',
      type: 'number',
      rules: [
        {
          validator: (rule, value, callback) => {
            const regex = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配最多两位小数
            if (value && !regex.test(value)) {
              callback('请输入最多两位小数的数字');
            } else {
              callback(); // 校验通过
            }
          },
        },
      ],
      visible: priceType === 'money',
    },
    {
      type: 'noForm',
      formItem: (
        <PackagingModel
          disabled={priceType !== 'money'}
          defaultDataList={goodsPackageList}
          ref={packagingRef}
          detail={data}
        >
          {' '}
        </PackagingModel>
      ),
    }
  ];
  const formItemsGroup4 = [
    {
      label: '上架类型',
      name: 'upType',
      type: 'radio',
      onChange: (e) => {
        setDefaultSetting({
          ...defaultSetting,
          upType: e.target.value,
        });
      },
      select: {
        now: '立刻上架',
        delay: '定时上架',
        off: '暂不上架',
      },
    },
    {
      label: '定时上架时间',
      name: 'upDelayTime',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      showTime: 'HH:mm',
      visible: upType === 'delay',
    },
    {
      label: '是否显示在店铺',
      name: 'showFlag',
      type: 'radio',
      select: {
        0: '否',
        1: '是',
      },
    },
  ];
  return (
    <Card title={id ? '编辑直播' : '新建直播'} style={{ position: 'relative' }}>
      <Row>
        <Col span={18}>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">基本信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItems}
            initialValues={{
              ...data,
              ...defaultSetting,
            }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">商品信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup3}
            initialValues={{ ...data, }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">上架设置</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup4}
            initialValues={{ ...data, upType, showFlag }}
          ></FormCondition>
        </Col>
        <div className="create_upload_btn">
          <Button onClick={() => fetchRoleEdit()} type="primary">
            {id ? '保存' : '创建直播'}
          </Button>
        </div>
      </Row>
      <SelectAccount
        disabledList={gatherList}
        onClose={() => {
          setModelVisible(false);
        }}
        onOk={(e) => setList(e)}
        visible={modelVisible}
      ></SelectAccount>
      <SelectGath
        disabledList={list}
        onClose={() => {
          setGatherVisible(false);
        }}
        onOk={(e) => setGatherList(e)}
        visible={gatherVisible}
      ></SelectGath>
    </Card>
  );
};
export default connect(({ loading }) => ({
  loading: loading.effects['liveStreaming/fakeSaveLive'],
}))(CreateLive);
